/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rbh.risk.service.impl;

import com.rbh.risk.service.AuthenticationService;
import com.rbh.risk.support.ProfileUserDetails;
import com.rbh.risk.util.MD5;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("authenticationService")
public class AuthenticationServiceImpl implements AuthenticationService, Serializable {

    private final static Logger logger = Logger.getLogger(AuthenticationService.class);
    @Autowired
    private AuthenticationManager authenticationManager; // specific for Spring Security

    @Transactional(readOnly = true)
    @Override
    public boolean login(String username, String password) {
        try {
            MD5 md5 = null;
            try {
                md5 = new MD5();
            } catch (NoSuchAlgorithmException ex) {
                logger.error(ex.getMessage());
            }
            md5.addToDigest(password);

            Authentication authenticate = this.authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, md5.getDigest().toLowerCase()));

            if (authenticate.isAuthenticated()) {
                SecurityContextHolder.clearContext();
                SecurityContextHolder.getContext().setAuthentication(authenticate);
                return true;
            }
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    @Transactional(readOnly = true)
    @Override
    public ProfileUserDetails getPrincipal() {
        return (ProfileUserDetails) ((SecurityContext) SecurityContextHolder.getContext()).getAuthentication().getPrincipal();
    }
}